package com.itxiaoxiong.chat.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


@Slf4j
public class ProxyServer {
    private final Socket socket;
    private final PrintWriter out;
    private final BufferedReader in;
    private final String userId;
    private volatile boolean running = true;
    private Thread proxyThread;

    public ProxyServer(String host, int port, String userId,HashMap<String, BlockingQueue<String>> userQueues) throws IOException {
        this.socket = new Socket(host, port);
        this.out = new PrintWriter(socket.getOutputStream(), true);
        this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        this.userId = userId;

        // 给TCP服务器发送用户ID
        out.println(userId);
        startProxy(userQueues);
    }

    private void startProxy(HashMap<String, BlockingQueue<String>> userQueues) {
        proxyThread = new Thread(() -> {
            try {
                String messageFromServer;
                while (running && (messageFromServer = in.readLine()) != null) {
                    // 处理来自服务器的消息
                    log.error("接收到服务器的消息: " + messageFromServer);

                    // 消息格式为 fromUserId: message
                    String[] parts = messageFromServer.split(":", 2);
                    if (parts.length == 2) {
                        String toUserId = parts[0].trim();
                        String message = parts[1].trim();
                        BlockingQueue<String> queue  = null;
                        log.error("进来了没有");
                        if (!userQueues.containsKey(toUserId)) {
                            queue = userQueues.put(toUserId, new LinkedBlockingQueue<>());
                            //log.error("创建新阻塞队列：" + toUserId);
                        } else {
                            //log.error("没创建新阻塞队列：" + toUserId);
                            queue = userQueues.get(toUserId);
                        }
                        //log.error("queue:"+ queue);
                        queue.offer(message);
                    }
                }
            } catch (IOException e) {
                if (running) {
                    System.out.println("Error in ProxyServer: " + e.getMessage());
                }
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("Error closing socket: " + e.getMessage());
                }
            }
        });
        proxyThread.start();
    }


    public void sendMessage(String message) {
        //给TCP服务器发消息
        out.println(message);
    }

    public void close() throws IOException {
        socket.close();
    }

}
